﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Data.SqlClient;
using System.Data;

namespace TAMSUP
{
    /// <summary>
    /// Interaction logic for penyewaan.xaml
    /// </summary>
    public partial class penyewaan : Window
    {
        private string ID = "";
        private bool isUbah = false;
        private bool isSelected = false;
        private DataSet ubah = new DataSet();
        public penyewaan()
        {
            InitializeComponent();
        }

        public penyewaan(string ID)
        {
            this.ID = ID;
            isUbah = true;
            InitializeComponent();
            label1.Content = "Ubah Penyewaan";
            addButton.Content = "Edit";
            cancelButton.Content = "Cancel";
            Title = "TAMS UP :: Form :: Ubah Penyewaan";
        }

        public penyewaan(DataRowView row)
        {
            InitializeComponent();
            reklameBox.Items.Add(row.Row.ItemArray.ElementAt(0).ToString());
            reklameBox.SelectedIndex = 0;
            isSelected = true;
        }
        
        private void addButton_Click(object sender, RoutedEventArgs e)
        {
            if (errorChecking())
            {
                if (!isUbah) {
                    try
                    {
                        homeWindow.Con.Open();

                        string _Date1 = mulaiDate.SelectedDate.Value.ToString("M/d/yyyy");
                        string _Date2 = selesaiDate.SelectedDate.Value.ToString("M/d/yyyy");

                        SqlDataAdapter da = new SqlDataAdapter("select * from penyewaan order by ID_Penyewaan", homeWindow.Con);
                        DataSet ds = new DataSet();
                        da.Fill(ds, "Daftar Penyewaan");

                        string _Insert = @"insert into penyewaan (ID_Penyewaan,Tanggal_Mulai,Tanggal_Selesai,Total_Harga,Nama_Klien,Keterangan)
                                  Values('P" + "','" + _Date1 + "','" + _Date2 + "','" +
                                                 hargaText.Text + "','" + klienText.Text + "','" + keteranganText.Text + "');";

                        SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);

                        // Execute the command
                        _cmd.ExecuteNonQuery();

                        da = new SqlDataAdapter("select IDENT_CURRENT('penyewaan')", homeWindow.Con);
                        ds = new DataSet();
                        da.Fill(ds, "Indeks Penyewaan");

                        int count = Int32.Parse(ds.Tables["Indeks Penyewaan"].Rows[0].ItemArray.ElementAt(0).ToString());

                        /*ini ditambahkan lagi seperti yang di form.xaml.cs*/

                        _Insert = @"insert into menyewa (ID_Reklame,ID_Penyewaan)
                                  Values('" + reklameBox.SelectedItem.ToString() + "','P" + addNol(count) + count + "');";

                        _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();

                        homeWindow.Con.Close();
                        MessageBox.Show("Berhasil menambahkan penyewaan baru", "Sewa Baru");
                        homeWindow.top.refresh();
                        restart();
                    }
                    catch (SqlException sqle)
                    {
                        MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                    }
                }
                else
                {
                    try
                    {
                        homeWindow.Con.Open();

                        string _Date1 = mulaiDate.SelectedDate.Value.ToString("M/d/yyyy");
                        string _Date2 = selesaiDate.SelectedDate.Value.ToString("M/d/yyyy");

                        string _Insert = @"update Penyewaan
                                            set Tanggal_Mulai = '" + _Date1 + "', Tanggal_Selesai = '" + _Date2 + "',  Total_Harga = '" + hargaText.Text +
                                                            "',  Nama_Klien = '" + klienText.Text + "',  Keterangan = '" + keteranganText.Text + "'" +
                                                            "where ID_Penyewaan = '" + ID + "';";

                        SqlCommand _cmd = new SqlCommand(_Insert, homeWindow.Con);

                        // Execute the command
                        _cmd.ExecuteNonQuery();

                        _Insert = @"update menyewa set ID_reklame = '" + reklameBox.SelectedItem.ToString() + "' where ID_Penyewaan = '" + ID + "';";

                        _cmd = new SqlCommand(_Insert, homeWindow.Con);
                        _cmd.ExecuteNonQuery();

                        homeWindow.Con.Close();
                        MessageBox.Show("Berhasil mengubah informasi penyewaan", "Ubah Sewa");
                        homeWindow.top.refresh();
                        homeWindow.top.Focus();
                        this.Close();
                    }
                    catch (SqlException sqle)
                    {
                        MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
                    }
                }
            }
        }

        private void restart()
        {
            Brush validColor = new SolidColorBrush(Color.FromRgb(200,200,200));
            reklameBox.SelectedIndex = -1;
            reklameBox.Background = validColor;
            hargaText.Text = "";
            hargaText.Background = validColor;
            klienText.Text = "";
            klienText.Background = validColor;
            keteranganText.Text = "";
            keteranganText.Background = validColor;
            mulaiDate.SelectedDate = DateTime.Now;
            mulaiDate.Background = validColor;
            selesaiDate.SelectedDate = DateTime.Now;
            selesaiDate.Background = validColor;
        }

        private Boolean errorChecking()
        {
            Boolean valid = true;
            Brush invalidColor = new SolidColorBrush(Color.FromRgb(255,225,0));
            Brush validColor = new SolidColorBrush(Color.FromRgb(200,200,200));
            int temp;
            if (reklameBox.SelectedIndex == -1)
            {
                reklameBox.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                reklameBox.Background = validColor;
            }
            if (hargaText.Text == "")
            {
                hargaText.Background = invalidColor;
                if (valid) valid = false;
            }
            else if (!Int32.TryParse(hargaText.Text.ToString(),out temp)) {
                hargaText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                hargaText.Background = validColor;
            }
            if ((klienText.Text == "") || (klienText.Text.Length > 50))
            {
                klienText.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                klienText.Background = validColor;
            }
            if (mulaiDate.SelectedDate >= selesaiDate.SelectedDate)
            {
                mulaiDate.Background = invalidColor;
                selesaiDate.Background = invalidColor;
                if (valid) valid = false;
            }
            else
            {
                mulaiDate.Background = validColor;
                selesaiDate.Background = validColor;
            }
            if (!valid)
            {
                MessageBox.Show("Ada kesalahan pengisian informasi penyewaan", "Invalid Information");
            }
            return valid;
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try {
                homeWindow.Con.Open();

                SqlDataAdapter da = new SqlDataAdapter("select ID_Reklame from Reklame except select ID_Reklame from Menyewa as a join penyewaan as b on a.ID_Penyewaan = b.ID_Penyewaan WHERE (DATEDIFF(day, b.Tanggal_selesai, GETDATE()) <= 0)", homeWindow.Con);
                DataSet ds = new DataSet();
                da.Fill(ds, "Daftar Reklame");

                mulaiDate.SelectedDate = DateTime.Now;
                selesaiDate.SelectedDate = DateTime.Now;

                if (!isSelected)
                {
                    int count = ds.Tables["Daftar Reklame"].Rows.Count + 1;

                    for (int i = 0; i < count - 1; i++)
                    {
                        reklameBox.Items.Add(ds.Tables["Daftar Reklame"].Rows[i].ItemArray.ElementAt(0).ToString());
                    }
                } 

                if (isUbah)
                {
                    da = new SqlDataAdapter("select * from penyewaan as a inner join menyewa as b on a.ID_Penyewaan = b.ID_Penyewaan where a.ID_Penyewaan = '" + ID + "';", homeWindow.Con);
                    ubah = new DataSet();
                    da.Fill(ubah, "Daftar Penyewaan");
                    reklameBox.Items.Add(ubah.Tables["Daftar Penyewaan"].Rows[0].ItemArray.ElementAt(10).ToString());
                    reklameBox.SelectedItem = ubah.Tables["Daftar Penyewaan"].Rows[0].ItemArray.ElementAt(10).ToString();
                    klienText.Text = ubah.Tables["Daftar Penyewaan"].Rows[0].ItemArray.ElementAt(4).ToString();
                    hargaText.Text = ubah.Tables["Daftar Penyewaan"].Rows[0].ItemArray.ElementAt(3).ToString();
                    keteranganText.Text = ubah.Tables["Daftar Penyewaan"].Rows[0].ItemArray.ElementAt(5).ToString();
                    mulaiDate.Text = ubah.Tables["Daftar Penyewaan"].Rows[0].ItemArray.ElementAt(1).ToString();
                    selesaiDate.Text = ubah.Tables["Daftar Penyewaan"].Rows[0].ItemArray.ElementAt(2).ToString();

                }
                homeWindow.Con.Close();
            }
            catch (SqlException sqle)
            {
                MessageBox.Show("Ada kesalahan pada koneksi ke server, silakan periksa jaringan.\n\n SQL error code : " + sqle.State, "Error : Connection Not Established");
            }
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (isUbah)
            {
                homeWindow.top.refresh();
                homeWindow.top.Focus();
                this.Close();
            }
            else
            {
                restart();
            }
        }

        private void hargaText_TextChanged(object sender, TextChangedEventArgs e)
        {

        }

        private void sewaWindow_Closed(object sender, EventArgs e)
        {
            homeWindow.top.refresh();
            homeWindow.top.Focus();
        }

        private string addNol(int x)
        {
            string temp = "";
            string angka = x.ToString();

            if (angka.Count() == 4)
            {
                temp = "0";
            }
            else if (angka.Count() == 3)
            {
                temp = "00";
            }
            else if (angka.Count() == 2)
            {
                temp = "000";
            }
            else if (angka.Count() == 1)
            {
                temp = "0000";
            }
            Console.WriteLine(temp);
            return temp;
        }
    }
}
